import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_github_login/progressdialog.dart';

//创建dio实例
Dio dio = Dio();

class HttpUtils {
  static HttpUtils get instance => _getInstance();
  static final HttpUtils _instance = HttpUtils();

  static HttpUtils _getInstance() {
    return _instance;
  }

  HttpUtils() {
    // 在构造函数里面添加拦截器
    dio.interceptors.add(CustomInterceptors());
  }

  //get方法 path和query参数
  Future get(path ) async {
    Response resp;
    try {
      resp = await dio.get(path);

      if (resp.statusCode == 200) {
        String val = resp.toString();
        return jsonDecode(val);
      } else {
        String val = resp.toString();
        return jsonDecode(val);
      }
    } catch (error) {
      return error;
    }
  }

  //post方法
  Future post(path, data) async {
    Response resp;
    try {
      resp = await dio.post(path, data: data);
      if (resp.statusCode == 200) {
        String val = resp.toString();
        return jsonDecode(val);
      } else {
        String val = resp.toString();

        return jsonDecode(val);
      }
    } catch (error) {
      return error;
    }
  }

  Future put(path, data) async {
    Response resp;
    try {
      resp = await dio.put(path, data: data);
      if (resp.statusCode == 200) {
        String val = resp.toString();
        return jsonDecode(val);
      } else {
        String val = resp.toString();
        return jsonDecode(val);
      }
    } catch (error) {
      return error;
    }
  }
}

class CustomInterceptors extends InterceptorsWrapper {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    //超时设置
    options.connectTimeout = 30000;
    options.receiveTimeout = 30000;
    //设置token
    //options.headers["Authorization"] = "Bearer ";
    //设置请求头
    options.headers['content-type'] = "application/json";

    print('------------------------请求开始------------------------');
    print('- 请求方式：${options.method}');
    print('- 请求数据: ${options.data}');
    print('- 请求头信息：${options.headers}');
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    print('------------------------请求结束------------------------');
    super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    print('------------------------请求出错------------------------');
    print('- 错误类型：${err.type}');
    print('- 错误信息：${err.message}');
    print('- error: $err');
    super.onError(err, handler);
  }
}
